import dynamic from 'next/dynamic';
import { useContext, useEffect, useRef } from 'react';
import { ChatContext } from '@/app/chat-context';
import type { OnChange } from '@monaco-editor/react';
// 动态导入 Monaco Editor
const MonacoEditor = dynamic(() => import('@monaco-editor/react'), {
  ssr: false
});

interface EditorProps {
  value: string;
  height?: number;
  language?: string;
  onChange?: OnChange;
}

export default function CustomMonacoEditor({
  value,
  height = 200,
  language = 'mysql',
  onChange,
}: EditorProps) {
  const { mode } = useContext(ChatContext);
  const editorRef = useRef(null);

  // 编辑器配置选项
  const editorOptions = {
    minimap: { enabled: false },
    wordWrap: 'on',
    scrollBeyondLastLine: false,
    automaticLayout: true,
    fontSize: 14,
    tabSize: 2,
    lineNumbers: 'on',
    folding: true,
    renderLineHighlight: 'all',
    suggestOnTriggerCharacters: true,
  };

  // 处理编辑器实例的挂载
  const handleEditorDidMount = (editor: any) => {
    editorRef.current = editor;
  };

  return (
    <div className="w-full ml-2">
      <MonacoEditor 
        width="100%"
        height={height}
        value={value}
        onChange={onChange}
        defaultLanguage={language}
        theme={mode === 'dark' ? 'vs-dark' : 'light'}
        options={editorOptions}
        onMount={handleEditorDidMount}
      />
    </div>
  );
}
